//
//  CallInProgressViewController.m
//  Voxper
//
//  Created by Erphan on 2/4/11.
//  Copyright 2011 Smonte. All rights reserved.
//

#import "CallInProgressViewController.h"
#import "VoxperAppDelegate.h"
#import "SipManager.h"
#import "UIManager.h"
#import <AVFoundation/AVFoundation.h>

@interface CallInProgressViewController(Private)
- (void)dismiss;
- (void)showKeypad:(BOOL)display animated:(BOOL)animated;
- (void)initRingtone;
- (void)playRingtone:(BOOL)bIsIncoming;
- (void)stopRingtone;
@end

@implementation CallInProgressViewController

@synthesize CallId = m_CallId;
@synthesize PushInvoked = m_bPushInvoked;
@synthesize InitalContactName = m_strInitialContactName;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        app = (VoxperAppDelegate *)[UIApplication sharedApplication].delegate;
    }
    return self;
}



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationReceived:) name:@"CallStateNotification" object:nil];
	[m_btnAcceptCall setHidden:YES];
	[m_btnCancelCall setHidden:YES];
	[m_btnEndCall setHidden:YES];
    [m_btnHideKeypad setHidden:YES];
    
	if (m_bPushInvoked) {
		m_lblStatus.text = @"connecting...";
		m_lblCallerId.text = m_strInitialContactName;
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(regNotificationReceived:) name:@"SipRegistration" object:nil];
		[m_btnEndCall setHidden:NO];
		m_btnEndCall.enabled = NO;
		m_bTheresNoIncomingCalls = YES;
	}
    
    [m_viewKeypad removeFromSuperview];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque animated:YES];
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    NSLog(@"Memory Issue--------------------->>>>");
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    //[m_ringtonePlayer release];
	[m_strInitialContactName release];
	[[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"Call In Progress: Dealloced");
    [super dealloc];
}

#pragma mark -
#pragma mark IBActions

- (IBAction)btnEndCall_Clicked:(id)sender {
	[app.manager dropCall:m_CallId];
}

- (IBAction)btnAcceptCall_Clicked:(id)sender {
    [self stopRingtone];
	[app.manager answerCall:m_CallId];
}

- (IBAction)btnCancelCall_Clicked:(id)sender {
	[app.manager declineCall:m_CallId];
}

- (IBAction)btnCallMenu_Clicked:(id)sender {
    UIButton *btn = (UIButton *)sender;
    
    btn.selected = !btn.selected;
    
    if ([btn.titleLabel.text isEqualToString:@"speaker"]) {
        [app.manager setSpeakerPhoneEnabled:btn.selected];
    } else if ([btn.titleLabel.text isEqualToString:@"keypad"]) {
        [self showKeypad:YES animated:YES];
    } else if ([btn.titleLabel.text isEqualToString:@"mute"]) {
        [app.manager setMute:btn.selected];
    } else if ([btn.titleLabel.text isEqualToString:@"addcall"]) {
        //[app.manager setMute:btn.selected];
    } else if ([btn.titleLabel.text isEqualToString:@"hold"]) {
        [app.manager setHold:YES :m_CallId];
    } else if ([btn.titleLabel.text isEqualToString:@"contacts"]) {
        //[app.manager setHold:YES :m_CallId];
    }
    
    NSString *strButtonText = btn.titleLabel.text;
    NSLog(@"BUTTON TEXT: %@", strButtonText);
}

- (IBAction)btnKeypad_Clicked:(id)sender {
    NSString *strButtonText = ((UIButton *)sender).titleLabel.text;
    NSLog(@"BUTTON TEXT: %@", strButtonText);
}

- (IBAction)btnHideKeyPad_Clicked:(id)sender {
    [self showKeypad:NO animated:YES];
}

#pragma mark -
#pragma mark Notifcations

- (void)regNotificationReceived:(NSNotification *)note {
	if ([note object]) {
		NSString *strInfo = (NSString *)[note object];
		
		NSLog(@"REGISTRATIONINFO: %@", strInfo);
		
		if ([strInfo isEqualToString:@"OK"]) {
			[self performSelector:@selector(checkIfThereIsNoIncomingCall) withObject:nil afterDelay:4];
		} else {
			m_lblStatus.text = @"Disconnected";
			[app.manager showRegistrationStatus];
			[self performSelector:@selector(dismiss) withObject:nil afterDelay:2];
		}
		
	} else {
		m_lblStatus.text = @"Disconnected";
		[app.manager showRegistrationStatus];
		[self performSelector:@selector(dismiss) withObject:nil afterDelay:1];
	}
}

- (void)notificationReceived:(NSNotification *)note {
	//NSLog(@"CALLSTATE: MAIN THREAD: %@", [NSThread isMainThread]?@"YES": @"NO");

	NSDictionary *dic = (NSDictionary *)[note userInfo];
	SipCallInfo *callInfo = (SipCallInfo *)[dic objectForKey:DIC_CALLINFO];
	if (callInfo.callId) {
		m_CallId = callInfo.callId;
	}
	
	//NSLog(@"CALLSTATUS: %d - CallerID: %@", [callInfo.state intValue], callInfo.remoteContact);
	switch(callInfo.state)
	{
		case 1:
			m_lblCallerId.text = callInfo.remoteInfo;
			m_lblStatus.text = @"Calling";
			[m_btnEndCall setHidden:NO];
			[m_btnAcceptCall setHidden:YES];
			[m_btnCancelCall setHidden:YES];
            m_bIsOutgoing = YES;
			break;
		case 2:
            m_bIsOutgoing = NO;
			m_lblCallerId.text = callInfo.remoteInfo;
			if (m_bPushInvoked) {
				[self btnAcceptCall_Clicked:nil];
				m_btnEndCall.enabled = YES;
				// there is an incoming call so don't dismiss the UI
				m_bTheresNoIncomingCalls = NO;
				break;
			}
			m_lblStatus.text = @"Incoming call";
			[m_btnEndCall setHidden:YES];
            [m_btnAcceptCall setHidden:NO];
            [m_btnCancelCall setHidden:NO];
            [self playRingtone:YES];
			break;
		case 3:
			m_lblCallerId.text = callInfo.remoteInfo;
            if (m_bIsOutgoing) {
                //[self playRingtone:YES];
            }
			break;
		case 5:
			m_lblStatus.text = @"Connected";
            
			[m_btnEndCall setHidden:NO];
			[m_btnAcceptCall setHidden:YES];
			[m_btnCancelCall setHidden:YES];
			break;
		case 6:
            [self stopRingtone];
			m_btnEndCall.enabled = NO;
			m_btnAcceptCall.enabled = NO;
			m_btnCancelCall.enabled = NO;
			m_lblStatus.text = @"Disconnected";
            //[self dismiss];
            //[self showKeypad:NO animated:YES];
			[self performSelector:@selector(dismiss) withObject:nil afterDelay:1];
			break;
	}
}

#pragma mark -
#pragma mark Private

- (void)initRingtone {
    // there's no need to init the system sound since it doesn't take much time, if it does init the sound and call init in view did appear etc.
}

- (void)playRingtone:(BOOL)bIsIncoming {
    NSLog(@"Playing ringtone");
    CFURLRef soundFileURLRef;
	OSStatus oStatus;
	CFBundleRef mainBundle = CFBundleGetMainBundle ();
    if (bIsIncoming) {
        soundFileURLRef = CFBundleCopyResourceURL (mainBundle, CFSTR ("ringtone"),
                                                   CFSTR ("caf"), NULL);
    } else {
        soundFileURLRef = CFBundleCopyResourceURL (mainBundle, CFSTR ("remoteringtone"),
                                                   CFSTR ("caf"), NULL);
    }
    
	oStatus = AudioServicesCreateSystemSoundID (soundFileURLRef, &aSoundID);
	if (oStatus == kAudioServicesNoError) {
		AudioServicesPlayAlertSound(aSoundID);
        // release the aSound in the stop section
    }
	else {
        NSLog(@"MuteSwitch is on, will not play ringtone");
        AudioServicesDisposeSystemSoundID(aSoundID);
    }
    
	CFRelease(soundFileURLRef);
}

- (void)stopRingtone {
    AudioServicesDisposeSystemSoundID(aSoundID);
}

- (void)dismiss {
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
	[app initiateUI];
	[self dismissModalViewControllerAnimated:YES];
}

- (void)checkIfThereIsNoIncomingCall {
	if (m_bTheresNoIncomingCalls) {
		[self dismiss];
	}
}

- (void)showKeypad:(BOOL)display animated:(BOOL)animated
{
	if (animated)
	{
		[UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDuration:0.5];
		
		[UIView setAnimationTransition:(display ?
										UIViewAnimationTransitionFlipFromLeft : UIViewAnimationTransitionFlipFromRight)
							   forView:m_viewContainer cache:YES];
	}
	if (display)
	{
        [m_viewCallMenu removeFromSuperview];
        [m_viewContainer addSubview:m_viewKeypad];
	}
	else
	{
        [m_viewContainer addSubview:m_viewCallMenu];
        [m_viewKeypad removeFromSuperview];
	}
	
	if (animated) {
		[UIView commitAnimations];
        
        [UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDuration:0.4];
		
		[UIView setAnimationTransition:UIViewAnimationTransitionNone
							   forView:m_btnEndCall cache:YES];
        if (display) {
            CGRect btnFrame = m_btnEndCall.frame;
            btnFrame.size.width = 142;
            m_btnEndCall.frame = btnFrame;
            [m_btnEndCall setImage:[UIImage imageNamed:@"btnendcall_small.png"] forState:UIControlStateNormal];
            [m_btnHideKeypad setHidden:NO];
        } else {
            CGRect btnFrame = m_btnEndCall.frame;
            btnFrame.size.width = 312;
            m_btnEndCall.frame = btnFrame;
            [m_btnEndCall setImage:[UIImage imageNamed:@"btnendcall.png"] forState:UIControlStateNormal];
            [m_btnHideKeypad setHidden:YES];
        }
        [UIView commitAnimations];
    }
}
@end
